<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="####添加权限1&amp;lt;uses-permission android:name=&amp;quot;android.permission.NFC&amp;quot; /&amp;gt;">
<meta name="keywords" content="Android、iOS、Web、React Native">
<meta property="og:type" content="article">
<meta property="og:title" content="Android-NFC(近程通信)使用">
<meta property="og:url" content="http://yoursite.com/blog/2018/08/06/Android-Special-Function/Android-NFC(近程通信)使用/index.html">
<meta property="og:site_name" content="凌浩雨_博客">
<meta property="og:description" content="####添加权限1&amp;lt;uses-permission android:name=&amp;quot;android.permission.NFC&amp;quot; /&amp;gt;">
<meta property="og:locale" content="default">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/3110861-b7a9237914049b2f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-08-06T11:09:16.146Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android-NFC(近程通信)使用">
<meta name="twitter:description" content="####添加权限1&amp;lt;uses-permission android:name=&amp;quot;android.permission.NFC&amp;quot; /&amp;gt;">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/3110861-b7a9237914049b2f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/blog/2018/08/06/Android-Special-Function/Android-NFC(近程通信)使用/"/>





  <title>Android-NFC(近程通信)使用 | 凌浩雨_博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">凌浩雨_博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/blog/blog/2018/08/06/Android-Special-Function/Android-NFC(近程通信)使用/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="凌浩雨">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="凌浩雨_博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Android-NFC(近程通信)使用</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-08-06T18:01:38+08:00">
                2018-08-06
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>####添加权限<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;uses-permission android:name=&quot;android.permission.NFC&quot; /&gt;</span><br></pre></td></tr></table></figure></p>
<a id="more"></a>
<p>####1. 读写文本<br>activity_main.xml<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;</span><br><span class="line">&lt;LinearLayout</span><br><span class="line">    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;</span><br><span class="line">    android:id=&quot;@+id/activity_main&quot;</span><br><span class="line">    android:orientation=&quot;vertical&quot;</span><br><span class="line">    android:layout_width=&quot;match_parent&quot;</span><br><span class="line">    android:layout_height=&quot;match_parent&quot;&gt;</span><br><span class="line"></span><br><span class="line">    &lt;EditText</span><br><span class="line">        android:id=&quot;@+id/editText&quot;</span><br><span class="line">        android:layout_width=&quot;match_parent&quot;</span><br><span class="line">        android:layout_height=&quot;wrap_content&quot;</span><br><span class="line">        android:hint=&quot;请输入要写入的文本&quot;/&gt;</span><br><span class="line"></span><br><span class="line">    &lt;TextView</span><br><span class="line">        android:hint=&quot;卡中内容&quot;</span><br><span class="line">        android:id=&quot;@+id/textView&quot;</span><br><span class="line">        android:layout_width=&quot;match_parent&quot;</span><br><span class="line">        android:layout_height=&quot;wrap_content&quot;/&gt;</span><br><span class="line">&lt;/LinearLayout&gt;</span><br></pre></td></tr></table></figure></p>
<p>MainActivity.java<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br></pre></td><td class="code"><pre><span class="line">public class MainActivity extends AppCompatActivity &#123;</span><br><span class="line">    private static final String TAG = &quot;MainActivity&quot;;</span><br><span class="line">    /**写入内容的文本框*/</span><br><span class="line">    private EditText mEditText;</span><br><span class="line">    /**显示NFC卡中的内容*/</span><br><span class="line">    private TextView mTextView;</span><br><span class="line"></span><br><span class="line">    /**NFC相关*/</span><br><span class="line">    /**NFC适配器*/</span><br><span class="line">    private NfcAdapter mNfcAdapter;</span><br><span class="line">    /**延时意图*/</span><br><span class="line">    private PendingIntent mPendingIntent;</span><br><span class="line">    /**检测的卡类型*/</span><br><span class="line">    private static String[][] sTechArr = null;</span><br><span class="line">    /**意图过滤器*/</span><br><span class="line">    private static IntentFilter[] sFilters = null;</span><br><span class="line">    static &#123;</span><br><span class="line">        try &#123;</span><br><span class="line">            sTechArr = new String[][]&#123;</span><br><span class="line">                    &#123;IsoDep.class.getName()&#125;, &#123;NfcV.class.getName()&#125;, &#123;NfcF.class.getName()&#125;,</span><br><span class="line">                    &#123;MifareUltralight.class.getName()&#125;, &#123;NfcA.class.getName()&#125;</span><br><span class="line">            &#125;;</span><br><span class="line">            // 如果这里不设置过滤器，就必须要在AndroidManifest.xml中为MainActivity设置过滤器</span><br><span class="line">            // 这里的ACTION在NfcAdapter中有四个选中，个人认为是在设置响应优先级</span><br><span class="line">            /**</span><br><span class="line">             *</span><br><span class="line">             &lt;intent-filter&gt;</span><br><span class="line">                 &lt;action android:name=&quot;android.nfc.action.NDEF_DISCOVERED&quot; /&gt;</span><br><span class="line">                 &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;</span><br><span class="line">                 &lt;data android:mimeType=&quot;text/plain&quot; /&gt;</span><br><span class="line">             &lt;/intent-filter&gt;</span><br><span class="line">             */</span><br><span class="line">            sFilters = new IntentFilter[]&#123;</span><br><span class="line">                    new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED, &quot;*/*&quot;)</span><br><span class="line">            &#125;;</span><br><span class="line">        &#125; catch (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onCreate(Bundle savedInstanceState) &#123;</span><br><span class="line">        super.onCreate(savedInstanceState);</span><br><span class="line">        setContentView(R.layout.activity_main);</span><br><span class="line"></span><br><span class="line">        initView();</span><br><span class="line">        initNfc();</span><br><span class="line">        // 判断当前手机是否支持NFC</span><br><span class="line">        if (null == mNfcAdapter) &#123;</span><br><span class="line">            // 如果为null,则为不支持。</span><br><span class="line">            Toast.makeText(this, &quot;当前设备不支持NFC功能!&quot;, Toast.LENGTH_SHORT).show();</span><br><span class="line">            return;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 初始化NFC</span><br><span class="line">     */</span><br><span class="line">    private void initNfc() &#123;</span><br><span class="line">        // 1. 初始化Nfc适配器</span><br><span class="line">        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);</span><br><span class="line">        // 2. 初始化延时意图</span><br><span class="line">        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onResume() &#123;</span><br><span class="line">        super.onResume();</span><br><span class="line">        // 3. 允许后台唤醒--此处是指应用处于不可见的状态时，将卡片贴近手机时，唤醒当前App。</span><br><span class="line">        // 如果sFilters为null,则为不过滤任何意图；如果sTechArr为null时，则为接收所有类型的卡片。</span><br><span class="line">        mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, sFilters, sTechArr);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onPause() &#123;</span><br><span class="line">        super.onPause();</span><br><span class="line">        // 4. 禁止后台唤醒</span><br><span class="line">        mNfcAdapter.disableForegroundDispatch(this);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onNewIntent(Intent intent) &#123;</span><br><span class="line">        super.onNewIntent(intent);</span><br><span class="line">        // 5. 重写OnIntent方法, 读取到的数据存储在intent中</span><br><span class="line">        // 获取到意图中的Tag数据</span><br><span class="line">        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);</span><br><span class="line">//        TAG: Tech [android.nfc.tech.NfcV, android.nfc.tech.Ndef]</span><br><span class="line">        Log.e(TAG, &quot;onNewIntent: &quot; + tag);</span><br><span class="line">        // 此处判断输入框mEditText的内容是否为空，如果为空，则为读取数据；如果不为空，则为写入数据</span><br><span class="line">        if (TextUtils.isEmpty(mEditText.getText().toString())) &#123;</span><br><span class="line">            // 数据为空，读取数据</span><br><span class="line">            readData(tag);</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            // 数据不为空，写入数据</span><br><span class="line">            writeData(tag);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 读取数据</span><br><span class="line">     * @param tag Tag</span><br><span class="line">     */</span><br><span class="line">    private void readData(Tag tag) &#123;</span><br><span class="line">        // 从Tag中获取Ndef信息</span><br><span class="line">        Ndef ndef = Ndef.get(tag);</span><br><span class="line">        try &#123;</span><br><span class="line">            // 连接</span><br><span class="line">            ndef.connect();</span><br><span class="line">//            readData: type: android.ndef.unknown, size: 250, message: NdefMessage [NdefRecord tnf=1 type=54 payload=027A68E4BDA0E5A5BD]</span><br><span class="line">            Log.e(TAG, &quot;readData: type: &quot; + ndef.getType() + &quot;, size: &quot; + ndef.getMaxSize() + &quot;, message: &quot; + ndef.getNdefMessage().toString());</span><br><span class="line">            // 获取NdefMessage消息</span><br><span class="line">            NdefMessage ndefMessage = ndef.getNdefMessage();</span><br><span class="line">            // 获取NdefRecord记录</span><br><span class="line">            //ndefMessage.getRecords();</span><br><span class="line">            // 遍历数组</span><br><span class="line">            StringBuilder stringBuilder = new StringBuilder();</span><br><span class="line">            // 文本</span><br><span class="line">            String text;</span><br><span class="line">            for (NdefRecord ndefRecord : ndefMessage.getRecords()) &#123;</span><br><span class="line">                text = parseNdefRecord(ndefRecord);</span><br><span class="line">                if (!TextUtils.isEmpty(text)) &#123;</span><br><span class="line">                    stringBuilder.append(text);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            // 设置文本</span><br><span class="line">            mTextView.setText(stringBuilder.toString());</span><br><span class="line">        &#125; catch (IOException | FormatException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 解析NdefRecord数据</span><br><span class="line">     * @param ndefRecord NdefRecord记录</span><br><span class="line">     */</span><br><span class="line">    private String parseNdefRecord(NdefRecord ndefRecord) &#123;</span><br><span class="line">        // 判断是否为文本格式数据</span><br><span class="line">        if (NdefRecord.TNF_WELL_KNOWN != ndefRecord.getTnf()) &#123;</span><br><span class="line">            return &quot;&quot;;</span><br><span class="line">        &#125;</span><br><span class="line">        if (!Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) &#123;</span><br><span class="line">            return &quot;&quot;;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        try &#123;</span><br><span class="line">            // 获得字节流</span><br><span class="line">            byte[] payload = ndefRecord.getPayload();</span><br><span class="line">            // 获得编码格式</span><br><span class="line">            String textEncoding = ((payload[0] &amp; 0x80) == 0) ? &quot;utf-8&quot; : &quot;utf-16&quot;;</span><br><span class="line">            // 获得语言编码长度</span><br><span class="line">            int languageCodeLength = payload[0] &amp; 0x3f;</span><br><span class="line">            // 语言编码</span><br><span class="line">            String languageCode = new String(payload, 1, languageCodeLength, &quot;US-ASCII&quot;);</span><br><span class="line">            // 获取文本</span><br><span class="line">            return new String(payload, languageCodeLength + 1, payload.length - languageCodeLength -1, textEncoding);</span><br><span class="line">        &#125; catch (UnsupportedEncodingException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        return &quot;&quot;;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 写数据</span><br><span class="line">     * @param tag Tag</span><br><span class="line">     */</span><br><span class="line">    private void writeData(Tag tag) &#123;</span><br><span class="line">        // 创建一个NdefMessage消息</span><br><span class="line">        NdefMessage ndefMessage = new NdefMessage(createTextRecord(mEditText.getText().toString()));</span><br><span class="line">        // 写入Tag</span><br><span class="line">        if (writeTag(ndefMessage, tag)) &#123;</span><br><span class="line">            mEditText.setText(&quot;&quot;);</span><br><span class="line">            Toast.makeText(this, &quot;写入成功&quot;, Toast.LENGTH_SHORT).show();</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            Toast.makeText(this, &quot;写入失败&quot;, Toast.LENGTH_SHORT).show();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 将NdefMessage消息写入Tag</span><br><span class="line">     * @param ndefMessage Ndef消息</span><br><span class="line">     * @param tag Tag</span><br><span class="line">     */</span><br><span class="line">    private boolean writeTag(NdefMessage ndefMessage, Tag tag) &#123;</span><br><span class="line">        try &#123;</span><br><span class="line">            // 获取Ndef</span><br><span class="line">            Ndef ndef = Ndef.get(tag);</span><br><span class="line">            // 连接</span><br><span class="line">            ndef.connect();</span><br><span class="line">            // 写入数据</span><br><span class="line">            ndef.writeNdefMessage(ndefMessage);</span><br><span class="line">            return true;</span><br><span class="line">        &#125; catch (IOException | FormatException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        return false;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 创建文本信息</span><br><span class="line">     * @param text 要写入的文本信息</span><br><span class="line">     */</span><br><span class="line">    private NdefRecord createTextRecord(String text) &#123;</span><br><span class="line">        // 设置语言</span><br><span class="line">        byte[] langBytes = Locale.CHINA.getLanguage().getBytes(Charset.forName(&quot;US-ASCII&quot;));</span><br><span class="line">        // 设置编码</span><br><span class="line">        Charset utfEncoding = Charset.forName(&quot;UTF-8&quot;);</span><br><span class="line">        // 要写入的二进制数据</span><br><span class="line">        byte[] textBytes = text.getBytes(utfEncoding);</span><br><span class="line">        int utfBit = 0;</span><br><span class="line">        // 将语言长度转化对应的字符</span><br><span class="line">        char status = (char)(utfBit + langBytes.length);</span><br><span class="line">        // 创建一个大小为 1(即语言长度转化对应的字符) + 语言字节长度 + 文本字节长度的字节数组</span><br><span class="line">        byte[] data = new byte[1 + langBytes.length + textBytes.length];</span><br><span class="line">        // 写入第一位数据</span><br><span class="line">        data[0] = (byte) status;</span><br><span class="line">        // 写入语言字节</span><br><span class="line">        System.arraycopy(langBytes, 0, data, 1, langBytes.length);</span><br><span class="line">        // 写入文本数据</span><br><span class="line">        System.arraycopy(textBytes, 0, data, langBytes.length + 1, textBytes.length);</span><br><span class="line">        // 创建一个NdefRecord记录</span><br><span class="line">        return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 初始化布局</span><br><span class="line">     */</span><br><span class="line">    private void initView() &#123;</span><br><span class="line">        mEditText = (EditText) this.findViewById(R.id.editText);</span><br><span class="line">        mTextView = (TextView) this.findViewById(R.id.textView);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>####2. NFC读写Uri<br>对NFC的配置信息相同，此处只是更改读取与写入的操作。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br></pre></td><td class="code"><pre><span class="line">    @Override</span><br><span class="line">    protected void onNewIntent(Intent intent) &#123;</span><br><span class="line">        super.onNewIntent(intent);</span><br><span class="line">        // 5. 重写OnIntent方法, 读取到的数据存储在intent中</span><br><span class="line">        // 获取到意图中的Tag数据</span><br><span class="line">        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);</span><br><span class="line">//        TAG: Tech [android.nfc.tech.NfcV, android.nfc.tech.Ndef]</span><br><span class="line">        Log.e(TAG, &quot;onNewIntent: &quot; + tag);</span><br><span class="line">        // 此处判断输入框mEditText的内容是否为空，如果为空，则为读取数据；如果不为空，则为写入数据</span><br><span class="line">        if (TextUtils.isEmpty(mEditText.getText().toString())) &#123;</span><br><span class="line">            // 数据为空，读取数据</span><br><span class="line">            readData(tag);</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            // 数据不为空，写入数据</span><br><span class="line">            writeData(tag);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 写入Uri</span><br><span class="line">     * http://www.baidu.com/</span><br><span class="line">     * @param tag</span><br><span class="line">     */</span><br><span class="line">    private void writeData(Tag tag) &#123;</span><br><span class="line">        // 创建一个Uri</span><br><span class="line">        Uri uri = Uri.parse(mEditText.getText().toString());</span><br><span class="line">        // 创建一个NdefMessage格式数据</span><br><span class="line">        NdefMessage ndefMessage = new NdefMessage(NdefRecord.createUri(uri));</span><br><span class="line">        if (writeTag(ndefMessage, tag)) &#123;</span><br><span class="line">            Toast.makeText(this, &quot;写入成功&quot;, Toast.LENGTH_SHORT).show();</span><br><span class="line">            mEditText.setText(&quot;&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 写入数据</span><br><span class="line">     * @param ndefMessage Ndef格式数据</span><br><span class="line">     * @param tag Tag</span><br><span class="line">     * @return true，写入成功；false，写入失败</span><br><span class="line">     */</span><br><span class="line">    private boolean writeTag(NdefMessage ndefMessage, Tag tag) &#123;</span><br><span class="line">        // 计算写入数据的长度</span><br><span class="line">        int size = ndefMessage.toByteArray().length;</span><br><span class="line">        try &#123;</span><br><span class="line">            // 获取Ndef</span><br><span class="line">            Ndef ndef = Ndef.get(tag);</span><br><span class="line">            if (null != ndef) &#123;</span><br><span class="line">                // 连接NFC卡片</span><br><span class="line">                ndef.connect();</span><br><span class="line">                // 判断NFC芯片是否可写</span><br><span class="line">                if (!ndef.isWritable()) &#123;</span><br><span class="line">                    Toast.makeText(this, &quot;卡片不可写&quot;, Toast.LENGTH_SHORT).show();</span><br><span class="line">                    return false;</span><br><span class="line">                &#125;</span><br><span class="line">                // 判断要写入的数据是否大于NFC芯片最大字节数</span><br><span class="line">                if (ndef.getMaxSize() &lt; size) &#123;</span><br><span class="line">                    Toast.makeText(this, &quot;写入数据过大&quot;, Toast.LENGTH_SHORT).show();</span><br><span class="line">                    return false;</span><br><span class="line">                &#125;</span><br><span class="line">                ndef.writeNdefMessage(ndefMessage);</span><br><span class="line">                return true;</span><br><span class="line">            &#125; else &#123;</span><br><span class="line">                // 获取一个格式化工具</span><br><span class="line">                NdefFormatable formatable = NdefFormatable.get(tag);</span><br><span class="line">                // 判断是否为空</span><br><span class="line">                if (null != formatable)&#123;</span><br><span class="line">                    // 连接</span><br><span class="line">                    formatable.connect();</span><br><span class="line">                    // 格式化并写入数据</span><br><span class="line">                    formatable.format(ndefMessage);</span><br><span class="line">                    Toast.makeText(this, &quot;格式化成功，并成功写入数据&quot;, Toast.LENGTH_SHORT).show();</span><br><span class="line">                &#125;else &#123;</span><br><span class="line">                    Toast.makeText(this, &quot;无法格式化&quot;, Toast.LENGTH_SHORT).show();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; catch (IOException | FormatException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        return false;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 读取数据</span><br><span class="line">     * @param tag Tag</span><br><span class="line">     */</span><br><span class="line">    private void readData(Tag tag) &#123;</span><br><span class="line">        try &#123;</span><br><span class="line">            // 获取Ndef</span><br><span class="line">            Ndef ndef = Ndef.get(tag);</span><br><span class="line">            // 连接</span><br><span class="line">            ndef.connect();</span><br><span class="line">            Log.e(TAG, &quot;readData: type: &quot; + ndef.getType() + &quot;, size: &quot; + ndef.getMaxSize()</span><br><span class="line">                    + &quot;, message: &quot; + ndef.getNdefMessage().toString());</span><br><span class="line">            // 获取Ndef格式数据</span><br><span class="line">            NdefMessage ndefMessage = ndef.getNdefMessage();</span><br><span class="line">            // 获取信息中的记录</span><br><span class="line">            NdefRecord[] records = ndefMessage.getRecords();</span><br><span class="line">            // 判断是否有数据</span><br><span class="line">            if (null != records &amp;&amp; records.length &gt; 0) &#123;</span><br><span class="line">                StringBuilder stringBuilder = new StringBuilder();</span><br><span class="line">                // 迭代</span><br><span class="line">                for (NdefRecord ndefRecord : records) &#123;</span><br><span class="line">                    Uri uri = ndefRecord.toUri();</span><br><span class="line">                    if (null != uri) &#123;</span><br><span class="line">                        stringBuilder.append(uri.toString());</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">                String string = stringBuilder.toString();</span><br><span class="line">                mTextView.setText(string);</span><br><span class="line">                if (string.startsWith(&quot;http://&quot;)) &#123;</span><br><span class="line">                    // 跳转网页</span><br><span class="line">                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(stringBuilder.toString())));</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            // 断开连接</span><br><span class="line">            ndef.close();</span><br><span class="line">        &#125; catch (IOException | FormatException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<p>####3. 读写非Ndef格式数据<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onNewIntent(Intent intent) &#123;</span><br><span class="line">        super.onNewIntent(intent);</span><br><span class="line">        // 5. 重写OnIntent方法, 读取到的数据存储在intent中</span><br><span class="line">        // 获取到意图中的Tag数据</span><br><span class="line">        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);</span><br><span class="line">        // 可打印出当前NFC芯片支持的NFC类型</span><br><span class="line">//        onNewIntent: TAG: Tech [android.nfc.tech.NfcA, android.nfc.tech.MifareUltralight, android.nfc.tech.NdefFormatable]</span><br><span class="line">        Log.e(TAG, &quot;onNewIntent: &quot; + tag);</span><br><span class="line">        // 此处判断输入框mEditText的内容是否为空，如果为空，则为读取数据；如果不为空，则为写入数据</span><br><span class="line">        if (TextUtils.isEmpty(mEditText.getText().toString())) &#123;</span><br><span class="line">            // 数据为空，读取数据</span><br><span class="line">            readData(tag);</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            // 数据不为空，写入数据</span><br><span class="line">            writeData(tag);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 写数据</span><br><span class="line">     * @param tag Tag</span><br><span class="line">     */</span><br><span class="line">    private void writeData(Tag tag) &#123;</span><br><span class="line">        // 获取到MifareUltralight</span><br><span class="line">        MifareUltralight ultralight = MifareUltralight.get(tag);</span><br><span class="line">        try &#123;</span><br><span class="line">            // 连接</span><br><span class="line">            ultralight.connect();</span><br><span class="line">            // Write 1 page (4 bytes).</span><br><span class="line">            // 往每一页写数据，最多写四个字节</span><br><span class="line">            ultralight.writePage(4,&quot;中国&quot;.getBytes(Charset.forName(&quot;gb2312&quot;)));</span><br><span class="line">            ultralight.writePage(5,&quot;美国&quot;.getBytes(Charset.forName(&quot;gb2312&quot;)));</span><br><span class="line">            ultralight.writePage(6,&quot;英国&quot;.getBytes(Charset.forName(&quot;gb2312&quot;)));</span><br><span class="line">            ultralight.writePage(7,&quot;法国&quot;.getBytes(Charset.forName(&quot;gb2312&quot;)));</span><br><span class="line">            Toast.makeText(this, &quot;写入成功&quot;, Toast.LENGTH_SHORT).show();</span><br><span class="line">            mEditText.setText(&quot;&quot;);</span><br><span class="line">            // 关闭连接</span><br><span class="line">            ultralight.close();</span><br><span class="line">        &#125; catch (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 读数据</span><br><span class="line">     * @param tag Tag</span><br><span class="line">     */</span><br><span class="line">    private void readData(Tag tag) &#123;</span><br><span class="line">        // 获取连接</span><br><span class="line">        MifareUltralight ultralight = MifareUltralight.get(tag);</span><br><span class="line">        try &#123;</span><br><span class="line">            // 连接</span><br><span class="line">            ultralight.connect();</span><br><span class="line">            byte[] bytes = ultralight.readPages(4);</span><br><span class="line">            mTextView.setText(new String(bytes, Charset.forName(&quot;gb2312&quot;)));</span><br><span class="line">            // 断开连接</span><br><span class="line">            ultralight.close();</span><br><span class="line">        &#125; catch (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<p>####4. AndroidBeam打开其他手机应用<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 测试方法， 将两部手机靠近，AndroidBeam接触时，两部手机界面同时缩小居中，轻触处理数据的手机一方，即可完成发送，</span><br><span class="line"> * 放松数据期间手机不能离开，离开之后即会断开连接，终止发送。</span><br><span class="line"> */</span><br><span class="line">public class MainActivity extends AppCompatActivity implements</span><br><span class="line">        NfcAdapter.CreateNdefMessageCallback, NfcAdapter.OnNdefPushCompleteCallback&#123;</span><br><span class="line">    private static final String TAG = &quot;MainActivity&quot;;</span><br><span class="line">    private NfcAdapter mNfcAdapter;</span><br><span class="line">    private PendingIntent mPendingIntent;</span><br><span class="line">    @Override</span><br><span class="line">    protected void onCreate(Bundle savedInstanceState) &#123;</span><br><span class="line">        super.onCreate(savedInstanceState);</span><br><span class="line">        setContentView(R.layout.activity_main);</span><br><span class="line">        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);</span><br><span class="line">        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()), 0);</span><br><span class="line"></span><br><span class="line">        // 设置发送消息的回调</span><br><span class="line">        mNfcAdapter.setNdefPushMessageCallback(this, this);</span><br><span class="line">        // 设置发送完成回调</span><br><span class="line">        mNfcAdapter.setOnNdefPushCompleteCallback(this, this);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onNewIntent(Intent intent) &#123;</span><br><span class="line">        super.onNewIntent(intent);</span><br><span class="line">        Toast.makeText(this, &quot;NFC靠近&quot;, Toast.LENGTH_SHORT).show();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 当有NFC靠近时调用该方法</span><br><span class="line">     */</span><br><span class="line">    @Override</span><br><span class="line">    public NdefMessage createNdefMessage(NfcEvent event) &#123;</span><br><span class="line">        // 将&quot;com.mazaiting.nfc2&quot;更换为另一部手机中已存在的应用包名</span><br><span class="line">        return new NdefMessage(NdefRecord.createApplicationRecord(&quot;com.mazaiting.nfc2&quot;));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 数据发送完成时调用方法</span><br><span class="line">     */</span><br><span class="line">    @Override</span><br><span class="line">    public void onNdefPushComplete(NfcEvent event) &#123;</span><br><span class="line">        Toast.makeText(this, &quot;发送完成&quot;, Toast.LENGTH_SHORT).show();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onResume() &#123;</span><br><span class="line">        super.onResume();</span><br><span class="line">        mNfcAdapter.enableForegroundDispatch(this,mPendingIntent,</span><br><span class="line">                null,null);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onPause() &#123;</span><br><span class="line">        super.onPause();</span><br><span class="line">        mNfcAdapter.disableForegroundDispatch(this);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>AndroidBeam接触时如下图：<br><img src="http://upload-images.jianshu.io/upload_images/3110861-b7a9237914049b2f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图1.png"></p>
<p>####5. AndroidBeam传送大文件<br>1). 添加权限，一定不能忘记<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;uses-permission android:name=&quot;android.permission.NFC&quot;/&gt;</span><br><span class="line">&lt;uses-permission android:name=&quot;android.permission.READ_EXTERNAL_STORAGE&quot;/&gt;</span><br><span class="line">&lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot;/&gt;</span><br></pre></td></tr></table></figure></p>
<p>2). 在assets文件夹放一张图片或者文件，或者直接指定手机中的文件地址。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line">public class MainActivity extends AppCompatActivity implements</span><br><span class="line">        NfcAdapter.CreateBeamUrisCallback, NfcAdapter.OnNdefPushCompleteCallback &#123;</span><br><span class="line">    private static final String TAG = &quot;MainActivity&quot;;</span><br><span class="line">    private NfcAdapter mNfcAdapter;</span><br><span class="line">    private PendingIntent mPendingIntent;</span><br><span class="line"></span><br><span class="line">    private final String targetFilename = &quot;/sdcard/image.jpg&quot;;</span><br><span class="line">    @Override</span><br><span class="line">    protected void onCreate(Bundle savedInstanceState) &#123;</span><br><span class="line">        super.onCreate(savedInstanceState);</span><br><span class="line">        setContentView(R.layout.activity_main);</span><br><span class="line">        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);</span><br><span class="line">        mPendingIntent = PendingIntent.getActivity(this,0,</span><br><span class="line">                new Intent(this,getClass()),0);</span><br><span class="line">        try&#123;</span><br><span class="line">            InputStream is = getResources().getAssets().open(&quot;image.jpg&quot;);</span><br><span class="line">            FileOutputStream fos = new FileOutputStream(targetFilename);</span><br><span class="line">            byte[] buffer = new byte[1024];</span><br><span class="line">            int len = 0;</span><br><span class="line">            while((len = is.read(buffer))!=-1)&#123;</span><br><span class="line">                fos.write(buffer,0,len);</span><br><span class="line">            &#125;</span><br><span class="line">            fos.close();</span><br><span class="line">            is.close();</span><br><span class="line">        &#125;catch (Exception e)&#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        // 设置回调</span><br><span class="line">        mNfcAdapter.setBeamPushUrisCallback(this, this);</span><br><span class="line">        mNfcAdapter.setOnNdefPushCompleteCallback(this, this);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Uri[] createBeamUris(NfcEvent event) &#123;</span><br><span class="line">        Uri[] uris = new Uri[1];</span><br><span class="line">        Uri uri =  Uri.parse(&quot;file://&quot; + targetFilename);</span><br><span class="line">        uris[0]=uri;</span><br><span class="line">        return uris;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onNewIntent(Intent intent) &#123;</span><br><span class="line">        super.onNewIntent(intent);</span><br><span class="line">        Toast.makeText(this, &quot;接触&quot;, Toast.LENGTH_SHORT).show();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onResume() &#123;</span><br><span class="line">        super.onResume();</span><br><span class="line">        mNfcAdapter.enableForegroundDispatch(this,mPendingIntent,</span><br><span class="line">                null,null);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onPause() &#123;</span><br><span class="line">        super.onPause();</span><br><span class="line">        mNfcAdapter.disableForegroundDispatch(this);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void onNdefPushComplete(NfcEvent event) &#123;</span><br><span class="line">        // 另一部手机接收的文件位置--/storage/emulated/0/beam/传输的文件名</span><br><span class="line">        Log.e(TAG, &quot;onNdefPushComplete: &quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>####</p>
<p>####</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/08/06/Android-Special-Function/Android-Material-Design设计风格/" rel="next" title="Android-Material-Design设计风格">
                <i class="fa fa-chevron-left"></i> Android-Material-Design设计风格
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/08/06/Android-Special-Function/Android-Status(状态栏)-着色/" rel="prev" title="Android-Status(状态栏)-着色">
                Android-Status(状态栏)-着色 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpeg"
                alt="凌浩雨" />
            
              <p class="site-author-name" itemprop="name">凌浩雨</p>
              <p class="site-description motion-element" itemprop="description">专业从事于移动端开发，Android与iOS均有涉及，主做Android开发与React Native开发</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">393</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">凌浩雨</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
